package com.haiyou.common.interceptor;

import com.haiyou.common.constant.MessageCode;
import com.haiyou.common.exception.BusinessException;
import com.haiyou.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author chenzeke
 * @date 2018/12/6 18:15
 */
@ControllerAdvice
@Slf4j
public class CommonExceptionHandler {
    /**
     * 全局异常捕捉处理
     *
     * @param e 通用异常
     * @return R
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public R exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return R.error(MessageCode.FORM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 全局运行异常
     *
     * @param e 运行异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public R exceptionHandler(RuntimeException e) {
        log.error(e.getMessage(), e);
        return R.error(MessageCode.FORM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 业务处理类型异常
     *
     * @param e 业务异常
     * @return R
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public R hqImExceptionHandler(BusinessException e) {
        log.error(e.getMessage(), e);
        return R.error(e.getCode(), e.getMessage());
    }

    /**
     * 表单验证异常捕获
     *
     * @param e 表单验证异常
     * @return R
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public R jsonBindExceptionHandler(BindException e) {
        log.info(e.getMessage(), e);
        return R.error(MessageCode.FORM_ERROR.getCode(), e.getMessage());
    }

}
